package net.hn.hnms.biz.quality.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import lombok.extern.slf4j.Slf4j;
import net.hn.hnms.biz.quality.domain.CoalQuality;
import net.hn.hnms.biz.quality.mapper.CommonMapper;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.core.utils.JsonUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 模板的读取类
 * Author chenlong
 */
@Slf4j
public class CoalQualityDataListener implements ReadListener<CoalQuality> {

    private static final int BATCH_COUNT = 100;
    private CommonMapper commonMapper;
    private List<CoalQuality> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private Long pubDate;

    public CoalQualityDataListener() {
    }

    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     *
     * @param
     */
    public CoalQualityDataListener(Long date, CommonMapper commonMapper) {
        this.commonMapper = commonMapper;
        this.pubDate = date;
    }

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        log.info("解析到一条头数据:{}", JsonUtils.toJsonString(headMap));

        Set[] i = new Set[]{headMap.keySet()};
        Arrays.stream(i).forEach(set -> {
            log.info(set.toString());
        });
        for (Set set : i) {
            log.info(set.toString());
        }
    }

    @Override
    public void onException(Exception exception, AnalysisContext context)  {

        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            int rowIndex=excelDataConvertException.getRowIndex()+1;
            int columnIndex=excelDataConvertException.getColumnIndex()+1;
            throw new HuaNengException(Constants.FAIL, "第"+rowIndex+"行，第"+columnIndex+"列解析异常，数据为:"+excelDataConvertException.getCellData().getStringValue());
        }

    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(CoalQuality data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JsonUtils.toJsonString(data));
        if (data != null) {

            if (isNull(data.getSellWay(), data.getCoalQualityDate(), data.getAsh(), data.getShaleContent(), data.getMoistureTotal(), data.getSalesVolume(), data.getNetCalorificValue(), data.getShaleContent())) {
                int i = cachedDataList.size() + 2;
                ExcelContentProperty excelContentProperty = new ExcelContentProperty();
                throw new ExcelDataConvertException(context.readRowHolder().getRowIndex(),1,context.readSheetHolder().getTempCellData(),excelContentProperty,"第" + i + "行内容格式不正确");

            }
            if (data.getSellWay().equals("外销")) {
                data.setSellWay("1");
            } else {
                data.setSellWay("0");
            }
            cachedDataList.add(data);

            // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
            if (cachedDataList.size() >= BATCH_COUNT) {
                saveData();
                // 存储完成清理 list
                cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
            }
        }
    }


    public boolean isNull(Object... o) {

        for (int i = 0; i < o.length; i++) {
            if (o[i] == null || o[i].equals("")) {
                return true;
            }
        }
        return false;
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {

        if (cachedDataList == null || cachedDataList.size() == 0) {
            throw new HuaNengException(Constants.FAIL, "文件为空！");
        }
        List<CoalQuality> list = new ArrayList<>();
//        Collections.copy(list, cachedDataList);

        Date date = new Date(pubDate);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        String importDate = sdf.format(date);

        for (int i = 0; i < cachedDataList.size(); i++) {
            String excelDate = sdf.format(cachedDataList.get(i).getCoalQualityDate());
            if (importDate.equals(excelDate)) {
                list.add(cachedDataList.get(i));
            }
        }

        log.info("{}条数据，开始存储数据库！1", list.size());

        commonMapper.insertBatch(list);
        cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        list = null;

        log.info("存储数据库成功！");
    }
}
